package com.glowdayz.glowmee;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.PatternChecker;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.AddItem;
import com.glowdayz.model.AdminTableCMD;
import com.glowdayz.model.EventCommentCMD;
import com.glowdayz.model.UserInfo;

public class ViewEvent extends Activity implements OnScrollListener, OnClickListener, OnItemClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	EditText addComment = null;
	ImageView okComment = null, joinBt = null;
	ListView eventCommentList = null;
	ArrayList<EventCommentCMD> list = null;
	DataAdapter adapter = null;
	// Footer 레이아웃
	LinearLayout llFooter = null;
	LinearLayout llHeader = null;
	
	ImageView eventImg = null;
	TextView eventTitle = null, eventDate = null, eventText = null, commentCnt = null;
	
	int paramId = 0;
	String url = "";
	boolean isComment = false;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 10;		// 한 페이지에 보일 수
	private int totalCount = 0;
	
	int bannerType = 0;
	String bannerUrl = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_event);
		
		am.addActivity(this);
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.top_share);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(this);
		okBt.setVisibility(View.GONE);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("이벤트 상세정보");
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_id", 0);
		
		addComment = (EditText) findViewById(R.id.addComment);
		okComment = (ImageView) findViewById(R.id.addPouchCommentBt);
		okComment.setOnClickListener(this);
		eventCommentList = (ListView) findViewById(R.id.eventCommentList);
		
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llHeader = (LinearLayout) inflater.inflate(R.layout.inc_event_header, null);
		eventCommentList.addHeaderView(llHeader);
		
		joinBt = (ImageView) llHeader.findViewById(R.id.joinBt);
		joinBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		joinBt.setOnClickListener(this);
		
		 // 메인 디지안과 별도로 레이아웃을 불러오기
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		// 리스트뷰에 추가
		eventCommentList.addFooterView(llFooter);
		eventCommentList.setOnScrollListener(this);
		eventCommentList.setOnItemClickListener(this);
        
        list = new ArrayList<EventCommentCMD>();
		adapter = new DataAdapter(this, list);
		eventCommentList.setAdapter(adapter);
		
		eventImg = (ImageView) findViewById(R.id.eventImg);
		eventTitle = (TextView) findViewById(R.id.eventTitle);
		eventDate = (TextView) findViewById(R.id.eventDate);
		eventText = (TextView) findViewById(R.id.eventText);
		commentCnt = (TextView) findViewById(R.id.commentCnt);
		
		(new CommentListWorker()).execute();
		
		(new EventWorker()).execute();
		
	}
	
	public class DataAdapter extends ArrayAdapter<EventCommentCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<EventCommentCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_event_comment_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			EventCommentCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				LinearLayout rootLayout = (LinearLayout) view.findViewById(R.id.rootLayout);
				rootLayout.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent arg1) {
						v.setBackgroundResource(android.R.drawable.list_selector_background);
						return false;
					}
				});
				
				LinearLayout commentLayout = (LinearLayout) view.findViewById(R.id.commentLayout);
				commentLayout.setBackgroundResource(R.drawable.box_review);
				
				TextView commentText = (TextView) view.findViewById(R.id.commentText);
				TextView nickName = (TextView) view.findViewById(R.id.nickName);
				TextView create_date = (TextView) view.findViewById(R.id.create_date);
				ImageView userImg = (ImageView) view.findViewById(R.id.userImg);
				userImg.setScaleType(ImageView.ScaleType.FIT_XY);
				
				commentText.setText(item.getEventComment());
				nickName.setText(item.getIdRegisterValue());
				create_date.setText(DateTime.getInstance().getDateTimeString3(item.getCreate_date()));
				
				if (item.getBm() == null) {
					userImg.setImageResource(R.drawable.profileimg);
				} else {
					userImg.setImageBitmap(item.getBm());
				}
			}
			return view;
		}
	}
	
	public class CommentListWorker extends AsyncTask<Object, EventCommentCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			String url = getResources().getString(R.string.server_url) + "/glowmee/listEventCommentXml.do?" +
					"page=" + page + "&count=" + pageSize + "&id=" + paramId;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idRegister = 0;
				String idRegisterValue = null;
				String eventComment = null;
				String create_date = null;
				String thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idRegister")) {
							parser.next();
							idRegister = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idRegisterValue")) {
							parser.next();
							idRegisterValue = parser.getText();
						} else if (tag.equals("eventComment")) {
							parser.next();
							eventComment = parser.getText();
						} else if (tag.equals("create_date")) {
							parser.next();
							create_date = parser.getText();
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							
							Bitmap bm = null;
							if (thumbnail != null) {
								try {
									URL url2 = new URL(getResources().getString(R.string.server_url) + thumbnail.trim()); 
									URLConnection conn = url2.openConnection(); 
									conn.connect(); 
									BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); 
									bm = BitmapFactory.decodeStream(bis); 
									bis.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
							
							EventCommentCMD item = new EventCommentCMD(idRegister, idRegisterValue, eventComment, create_date, thumbnail, bm);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(EventCommentCMD... param) {
			adapter.add(param[0]);
			isComment = true;
		}

		@Override
		protected void onPostExecute(Object param) {
			if (isComment == false) {
				eventCommentList.setDividerHeight(0);
			}
			llFooter.setVisibility(View.GONE);
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new CommentListWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				(new CommentListWorker()).execute();
			}
		}
	}
	
	public class EventWorker extends AsyncTask<Object, AdminTableCMD, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ViewEvent.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			String url = getResources().getString(R.string.server_url) + "/glowmee/viewEventXml.do?id=" + paramId;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				String boardTitle = null;
				String boardText = null;
				String start_date = null;
				String end_date = null;
				int eventLinkType = 0;
				String eventLinkCode = null;
				int comment_count = 0;
				String thumbnail = null;
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("boardTitle")) {
							parser.next();
							boardTitle = parser.getText();
						} else if (tag.equals("boardText")) {
							parser.next();
							boardText = parser.getText();
						} else if (tag.equals("start_date")) {
							parser.next();
							start_date = parser.getText();
						} else if (tag.equals("end_date")) {
							parser.next();
							end_date = parser.getText();
						} else if (tag.equals("eventLinkType")) {
							parser.next();
							eventLinkType = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("eventLinkCode")) {
							parser.next();
							eventLinkCode = parser.getText();
						} else if (tag.equals("comment_count")) {
							parser.next();
							comment_count = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("thumbnail")) {
							parser.next();
							thumbnail = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							AdminTableCMD item = new AdminTableCMD(
									eventLinkType, eventLinkCode, boardTitle, boardText, start_date, end_date, comment_count, thumbnail);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AdminTableCMD... param) {
			long nowTime = Long.parseLong(DateTime.getInstance().getNowDateTimeString());
			long startTime = Long.parseLong(param[0].getStart_date().trim());
			long endTime = Long.parseLong(param[0].getEnd_date().trim());
			if ((nowTime < startTime) || (nowTime > endTime)) {
				joinBt.setVisibility(View.GONE);
			} else {
				joinBt.setVisibility(View.VISIBLE);
				eventDate.setText(DateTime.getInstance().getDateTimeString2(
						param[0].getStart_date()) + "~" + DateTime.getInstance().getDateTimeString2(param[0].getEnd_date()));
			}
			eventImg.setScaleType(ImageView.ScaleType.FIT_XY);
			ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + param[0].getCreate_date().trim(), eventImg);
			eventTitle.setText(param[0].getBoardTitle());
			eventText.setText(param[0].getBoardText());
			commentCnt.setText("댓글(" + param[0].getComment_count() + ")");
			bannerType = param[0].getEventLinkType();
			bannerUrl = param[0].getEventLinkCode();
			if (bannerType == 21) {
				joinBt.setVisibility(View.GONE);
			}
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new EventWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.addPouchCommentBt:
			if (UserInfo.getInstance().getUSER_ID() == 0) {
				AlertDialog.Builder confirm = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
				confirm.setTitle("로그인 안내");
				confirm.setMessage("로그인 이후에 서비스 이용이 가능합니다.");
				confirm.setCancelable(false);
				confirm.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(ViewEvent.this, Login.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
						startActivity(intent);
						return;
					}
				});
				confirm.create();
				confirm.show();
			} else {
				String commentText = addComment.getText().toString().trim();
				if (commentText.equals("")) {
					Toast.makeText(this, "댓글 내용을 입력하세요.", Toast.LENGTH_SHORT).show();
					return;
				}
				url = getResources().getString(R.string.server_url) +  "/glowmee/addEventCommentXml.do?" +
						"rId=" + UserInfo.getInstance().getUSER_ID() + "&bId=" + paramId + "&comment=" + commentText;
				(new AddWorker()).execute();
			}
			
			break;
			
		case R.id.joinBt:
			url = getResources().getString(R.string.server_url) +  "/glowmee/addEventJoinXml.do?" +
					"rId=" + UserInfo.getInstance().getUSER_ID() + "&bId=" + paramId;
			(new JoinWorker()).execute();
			break;
			
		case R.id.okBt:
			AlertDialog.Builder temp = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
			temp.setMessage("준비중입니다.");
			temp.setCancelable(false);
			temp.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			temp.create();
			temp.show();
			break;
		}
	}
	
	public class AddWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ViewEvent.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}
		
		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				if (bannerType == 21) {
					url = getResources().getString(R.string.server_url) +  "/glowmee/addEventJoinXml.do?" +
							"rId=" + UserInfo.getInstance().getUSER_ID() + "&bId=" + paramId;
					(new JoinWorker()).execute();
				} else {
					AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
					alert.setTitle("등록 성공");
					alert.setMessage(param[0].getRtmsg());
					alert.setCancelable(false);
					alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(ViewEvent.this, ViewEvent.class);
							intent.putExtra("PARAM_id", paramId);
							startActivity(intent);
						}
					});
					alert.create();
					alert.show();
				}
			} else {
				AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
				alert.setTitle("등록 실패");
				alert.setMessage(param[0].getRtmsg());
				alert.setCancelable(false);
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
				alert.create();
				alert.show();
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new AddWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	public class JoinWorker extends AsyncTask<Object, AddItem, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ViewEvent.this);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				String rt = null;
				String rtmsg = null;
				int seq = 0;
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("rt")) {
							parser.next();
							rt = parser.getText();
						} else if (tag.equals("rtmsg")) {
							parser.next();
							rtmsg = parser.getText();
						} else if (tag.equals("seq")) {
							parser.next();
							seq = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("JSPglowmee")) {
							AddItem item = new AddItem(rt, rtmsg, seq);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(AddItem... param) {
			
			if (param[0].getRt().equals("SUCCESS")) {
				Intent intent = null;
				switch (bannerType) {
				case 13:
					intent = new Intent(Intent.ACTION_VIEW, Uri.parse(bannerUrl));
					startActivity(intent);
					break;
					
				case 14:
					intent = new Intent(ViewEvent.this, WebPage.class);
					intent.putExtra("PARAM_bannerUrl", bannerUrl);
					startActivity(intent);
					break;
					
				case 15:
					intent = new Intent(ViewEvent.this, AddPouch.class);
					startActivity(intent);
					break;
					
				case 16:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewPouch.class);
						intent.putExtra("PARAM_paramId", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 17:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewProduct.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 18:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewEvent.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 19:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewNotice.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 20:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ProfileHome.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 21:
					intent = new Intent(ViewEvent.this, ViewEvent.class);
					intent.putExtra("PARAM_id", paramId);
					startActivity(intent);
				}
			} else {
				Intent intent = null;
				switch (bannerType) {
				case 13:
					intent = new Intent(Intent.ACTION_VIEW, Uri.parse(bannerUrl));
					startActivity(intent);
					break;
					
				case 14:
					intent = new Intent(ViewEvent.this, WebPage.class);
					intent.putExtra("PARAM_bannerUrl", bannerUrl);
					startActivity(intent);
					break;
					
				case 15:
					intent = new Intent(ViewEvent.this, AddPouch.class);
					startActivity(intent);
					break;
					
				case 16:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewPouch.class);
						intent.putExtra("PARAM_paramId", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 17:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewProduct.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 18:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewEvent.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 19:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ViewNotice.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
					
				case 20:
					if (PatternChecker.getInstance().isNum(bannerUrl)) {
						intent = new Intent(ViewEvent.this, ProfileHome.class);
						intent.putExtra("PARAM_id", Integer.parseInt(bannerUrl));
						startActivity(intent);
					}
					break;
				}
			}
			
		}

		@Override
		protected void onPostExecute(Object param) {
			CDialog.hideLoading();
		}

		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ViewEvent.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new JoinWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2 > 0) {
			EventCommentCMD select = adapter.getItem(arg2 - 1);
			Intent intent = new Intent(this, ProfileHome.class);
			intent.putExtra("PARAM_id", select.getIdRegister());
			startActivity(intent);
		}
		
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}
	
}
